'''
Copyright: 
Descripttion: 
version: 
Author: chengx
Date: 2021-10-15 14:54:05
LastEditors: chengx
LastEditTime: 2022-03-13 16:13:32
'''
import sys
from sklearn.preprocessing import  StandardScaler
import numpy as np  
import matplotlib.pyplot as plt 
from sklearn.model_selection import train_test_split
from sklearn.metrics import roc_auc_score
from sklearn.metrics import confusion_matrix
from sklearn import svm



def readData(rand):
    x = np.load('./data/AvrData.npy')
    y = np.load('./data/AvrLabel.npy')

    print(x.shape,y.shape)

    import scipy.signal
    # x = scipy.signal.savgol_filter(x, 17, 7, deriv=1)  # 一阶导数处理

    x_abnom = x[~(y==0)] # 标签不为0的是异常
    x_nom = x[y==0]

    X_train, X_nom_test = train_test_split(x_nom, train_size = 0.5, random_state = rand)
    X_test = np.concatenate([X_nom_test,x_abnom],axis = 0)
    y_test = np.concatenate([np.zeros(len(X_nom_test)),np.ones(len(x_abnom))])
    print('X_train.shape, X_test.shape,y_test.shape',X_train.shape, X_test.shape, y_test.shape)

    def preProcess(X_train,X_test): # 数据预处理
        sc = StandardScaler()#去均值和方差归一化
        X_train = sc.fit_transform(X_train) # 先在训练集上拟合fit，找到该part的整体指标，然后进行转换transform
        X_test = sc.transform(X_test) # 对剩余的数据采用上面相同的指标进行transform
        return X_train, X_test
    X_train,X_test = preProcess(X_train,X_test)

    return X_train, X_test, y_test,



def main(X_test,y_test):
    clf = svm.OneClassSVM(nu=0.5, kernel="linear",gamma='auto').fit(X_train)  #设定训练误差nu

    y_pred_test = clf.predict(X_test)
    # ocsvm输出为 负样本：-1，正样本: 1
    for i in range(y_pred_test.shape[0]):
        if y_pred_test[i]==-1:
            y_pred_test[i]=0

    tn, fp, fn, tp = confusion_matrix(y_test, y_pred_test).ravel()
    prec = tp / np.maximum(tp + fp, sys.float_info.epsilon)
    recall = tp / np.maximum(tp + fn, sys.float_info.epsilon)
    f1 = 2.0 * prec * recall / np.maximum(prec + recall, sys.float_info.epsilon)

    auc = roc_auc_score(y_test, y_pred_test)
    print('auc',auc)
    print('tn,fp,fn,tp',tn,fp,fn,tp)
    print('prec:',prec)
    print('recall:',recall)
    print('f1:',f1)
    return auc,prec,recall,f1

if __name__ == '__main__':
    AC = []
    PC = []
    RC = []
    FC = []
    for i in range(10):
        X_train,X_test,y_test = readData(i)
        auc,prec,recall,f1 = main(X_test,y_test)
        AC.append(auc)
        PC.append(prec)
        RC.append(recall)
        FC.append(f1)

    print('auc',list(np.round(AC,3)))
    print('precision',list(np.round(PC,3)))
    print('recall',list(np.round(RC,3)))
    print('f1-score',list(np.round(FC,3)))